package com.example.armmvvm.ui.fallview

import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.lifecycleScope
import com.google.android.material.bottomsheet.BottomSheetBehavior
import kotlinx.coroutines.launch

/**
 *
 * 文件描述：
 *   将[layoutResId]的界面填充到带有Behavior的[viewContainer]中；
 *   并通过[BottomFallViewSetting]配置弹窗的模式、显示高度和回调等；
 *   [lifecycleOwner]和[viewContainer]相同时,使用同一个[BottomFallViewController],
 *   确保一个[viewContainer]同一时间只展示一个[BottomFallView];
 *   [viewContainer]和[layoutResId]相同时会复用View,复用时需要对一些界面复原,
 *   以及在[bottomFallViewSetting]的高度计算也需要特殊处理;
 *
 *   [updateView]：更新界面数据
 *   [afterShow]：加载界面后调用,此时界面已经添加到[viewContainer]
 *   [bottomFallViewSetting]：设置[BottomFallViewSetting.mode]展示模式等参数
 * 注意:
 *   [dismiss]后,[dismissListener]会重置
 *
 * @author 创建人 ：yanghaozhang
 * @version 1.0
 * @package 包名 ：com.augurit.agmobile.agwater5.drainage.pipereview.base
 * @createTime 创建时间 ：2021/3/26
 * @modifyBy 修改人 ：
 * @modifyTime 修改时间 ：
 * @modifyMemo 修改备注：
 */
abstract class BottomFallView(
    lifecycleOwner: LifecycleOwner,
    val viewContainer: ViewGroup,
    val layoutResId: Int,
    val state: Int = BottomSheetBehavior.STATE_COLLAPSED
) : BaseFallView(lifecycleOwner) {

    var fallViewSetting: BottomFallViewSetting? = null

    // 弹窗BottomBehavior的管理者
    protected val controller = BottomFallViewController.getInstance(viewContainer, lifecycleOwner)

    override fun show() {
        lifecycleOwner.lifecycle.addObserver(this)
        lifecycleOwner.lifecycleScope.launch {
            val attachView = controller.attachView(layoutResId)
            updateView(attachView)
            controller.showBottomView(createBottomFallViewSetting(attachView), state)
            afterShow(attachView)
        }
    }

    override fun dismiss() {
        if (isShowing()) {
            controller.hideBottomView()
        }
    }

    override fun isShowing(): Boolean {
        return controller.isShowing() && controller.currentFallView == fallViewSetting
    }

    private fun createBottomFallViewSetting(view: View): BottomFallViewSetting {
        return (bottomFallViewSetting(view) ?: BottomFallViewSetting(view)).apply {
            fallViewSetting = this
            hideCallBack = {
                onDismiss()
            }
        }
    }

    //-----------------子类实现方法--------------------------

    /**
     * 监听Behavior状态改变等
     */
    open fun bottomFallViewSetting(view: View): BottomFallViewSetting? = null

}